#include <string.h>
#include <unistd.h>
#include <errno.h>
#include "BSocketFile.h"

void BSocketFile_init(BSocketFile *file, unsigned char *buf, unsigned int buf_len, int sock_id) {
    memset(file, 0, sizeof(BSocketFile));
    file->rbuf = buf;
    file->rbuf_len = buf_len;
    file->socket_id = sock_id;
    file->rdata_len = 0;
    file->ridx = 0;
    file->widx = 0;
    file->wbuf_len = 0;
    file->wbuf = 0;
}

#include <stdio.h>

int BSocketFile_read(BSocketFile *file, unsigned char *ch) {
    int ret;
    //读完缓冲区
    if (file->ridx >= file->rdata_len) {
        ret = read(file->socket_id, file->rbuf, file->rbuf_len);        //更新缓冲区
        if (ret <= 0) {
            if ((errno == EAGAIN) && ret < 0) {
                //没有数据
                file->rdata_len = 0;
                file->ridx = 0;
                return BSOCKETFILE_RET_WAIT;
            } else {
                file->rdata_len = 0;
                file->ridx = 0;
                return BSOCKETFILE_RET_ERROR;
            }
        }
        file->rdata_len = (unsigned int)ret;
        file->ridx = 0;
    }
    *ch = file->rbuf[file->ridx];
    file->ridx++;
    return BSOCKETFILE_RET_SUCCEED;
}

int BSocketFile_wirte(BSocketFile *file, unsigned char *data, unsigned data_len) {
    int ret;
    //第一次初始化
    if (file->wbuf == 0) {
        file->wbuf = data;
        file->wbuf_len = data_len;
    }
    //未发送完成继续
    if (file->widx < file->wbuf_len) {
        ret = write(file->socket_id, file->wbuf + file->widx, file->wbuf_len - file->widx);
        if (ret <= 0) {
            if ((errno == EWOULDBLOCK || errno == EAGAIN) && ret < 0) {
                //缓冲区满,等待
                return BSOCKETFILE_RET_WAIT;
            } else {
                //断开连接
                file->wbuf = 0;
                file->wbuf_len = 0;
                file->widx = 0;
                return BSOCKETFILE_RET_ERROR;
            }
        } else {
            //保存发送个数
            file->widx += ret;
            return BSOCKETFILE_RET_WAIT;
        }
    }
    if (file->widx >= file->wbuf_len) {
        //发送完成
        file->wbuf = 0;
        file->wbuf_len = 0;
        file->widx = 0;
        return BSOCKETFILE_RET_SUCCEED;
    }
}


